# -*- coding: utf8 -*-

import string
from puppy.result import ResultFilter

class ExclusionFilter(ResultFilter):
  """
  Filters search results based on the results' suitability for children.
  
  Options:
  
  * threshold (double): confidence score to accept a page (e.g. 0.5)
  """
  
  def __init__(self, options=""):
    """Constructor for ExclusionFilter."""
    super(ExclusionFilter, self).__init__(options)
    self.info = "Filters search results based on a exclusion list."
    self.exclusion_list_string = " ".join(filter(str.isalpha, self.options['terms'].replace('+', ' ').lower().split()))
  
  def matches_exclusion_list(self, input_string):
    """
    Removes results that includes words contained in exclusion list.
    
    Parameters:
      
    * exclusion_list_string: string with words included in the black list
    * input_string: string with words separated by blank spaces 
    
    Returns:
    
    * true: if any of the words of the input string is included in the exclusion list 
      false: in other case          
    """
    input_list = input_string.split()

    for input in input_list:  
      try:  
        input_filtered = "".join(filter(str.isalpha, list(input.lower())))
      except TypeError:
        tmp = input.encode("iso-8859-1").lower()
        input_filtered = "".join(filter(str.isalpha, list(tmp)))
             
      if input_filtered in self.exclusion_list_string:
        if input_filtered not in ' ':
          return True
      
    return False

  def run(self, results):
    '''
    Filters the document list according to exclusion list.
    
    Parameters:
      
    * results (puppy.model.Opensearch.Response): results to be filtered
    
    Returns:
    
    * results_returned (puppy.model.Opensearch.Response): filtered results
          
    '''       
    
    
    i = 0
    for item in results.items:
      if self.matches_exclusion_list(item.title) or self.matches_exclusion_list(item.description):
        del results.items[i]
      else:
        i = i + 1
        
    # Return the filtered search result
    results_returned = results
    
    return results_returned
  
